package com.zh.rocketmq.mqmsg;

import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

/**
 * @author Zhou
 * @date 17:34 2025/10/20
 */
@Component
@RocketMQTransactionListener
public class TransactionListenerImpl implements RocketMQLocalTransactionListener {

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        // 执行本地事务逻辑，根据业务情况返回事务的提交或回滚状态
        try {
            // 模拟本地事务处理逻辑
            System.out.println("本地事务执行 ...");

            if (localSaveTransaction()) {
                return RocketMQLocalTransactionState.COMMIT;
            } else {
                return RocketMQLocalTransactionState.ROLLBACK;
            }
        } catch (Exception e) {
            return RocketMQLocalTransactionState.ROLLBACK;
        } finally {
            System.out.println("本地事务执行完成 ...");
        }
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        // 事务回查逻辑，确认本地事务的最终状态
        System.out.println("Checking local transaction...");

        //根据消息中的 订单ID 查询DB中是否已经落库
        // 根据本地事务的处理结果返回 COMMIT_MESSAGE 或 ROLLBACK_MESSAGE
        System.out.println("local transaction check success");

        return RocketMQLocalTransactionState.COMMIT;
    }

    private boolean localSaveTransaction() {
        // 模拟本地事务处理订单落库
        try {
            System.out.println("db save goods_order ...");
            Thread.sleep(1000);
            System.out.println("db save goods_order success ...");
            return true;
        } catch (InterruptedException e) {
            System.out.println("db save goods_order failed ...");
            return false;
        }
    }
}
